<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Exception;
use App\Utils\RedisUtil;
use App\Http\Middleware\ApiStatistics;

class TestController extends BaseController
{
    /**
     * 测试 Redis 连接
     */
    public function testRedis()
    {
        $ip='127.0.230';
        $key='ip:blacklist'.'_'.$ip;
        
        RedisUtil::setData($key,$ip,5*60);
        $data = RedisUtil::getData($key);
        //dd($data);
    }

    /**
     * 获取今日统计
     */
    public function getTodayStats()
    {
        $stats = ApiStatistics::getDailyStatistics();
        
        return response()->json([
            'success' => true,
            'message' => '今日API统计',
            'data' => $stats ?: [
                'total_requests' => 0,
                'avg_response_time' => 0,
                'status_codes' => [],
                'methods' => []
            ]
        ]);
    }

    /**
     * 获取指定日期统计
     */
    public function getDateStats(Request $request)
    {
        
        $date=$request->json("date");
        // 验证日期格式
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            return response()->json([
                'success' => false,
                'message' => '日期格式错误，请使用 YYYY-MM-DD 格式'
            ], 400);
        }
        
        $stats = ApiStatistics::getDailyStatistics($date);
        
        return response()->json([
            'success' => true,
            'message' => $date . ' API统计',
            'data' => $stats ?: [
                'total_requests' => 0,
                'avg_response_time' => 0,
                'status_codes' => [],
                'methods' => []
            ]
        ]);
    }
    
    /**
     * 获取当前小时统计
     */
    public function getCurrentHourStats()
    {
        $stats = ApiStatistics::getHourlyStatistics();
        
        return response()->json([
            'success' => true,
            'message' => '当前小时API统计',
            'data' => $stats ?: [
                'total_requests' => 0,
                'avg_response_time' => 0,
                'status_codes' => [],
                'methods' => []
            ]
        ]);
    }
    
    /**
     * 获取指定小时统计
     */
    public function getHourStats(Request $request)
    {
        $hour=$request->json("date");
        // 验证小时格式：YYYY-MM-DD-HH
        if (!preg_match('/^\d{4}-\d{2}-\d{2}-\d{2}$/', $hour)) {
            return response()->json([
                'success' => false,
                'message' => '小时格式错误，请使用 YYYY-MM-DD-HH 格式'
            ], 400);
        }
        
        $stats = ApiStatistics::getHourlyStatistics($hour);
        
        return response()->json([
            'success' => true,
            'message' => $hour . ' 时API统计',
            'data' => $stats ?: [
                'total_requests' => 0,
                'avg_response_time' => 0,
                'status_codes' => [],
                'methods' => []
            ]
        ]);
    }
    
    /**
     * 获取IP统计信息
     */
    public function getIpStats(Request $request)
    {
        $ip = $request->json('ip', $request->ip());
        $date = $request->json('date', now()->format('Y-m-d'));
        
        $stats = ApiStatistics::getIpStatistics($ip, $date);
        
        return response()->json([
            'success' => true,
            'message' => 'IP统计信息',
            'ip' => $ip,
            'date' => $date,
            'data' => $stats ?: [
                'request_count' => 0,
                'last_access' => '无记录',
                'user_agent' => '无记录',
                'status_codes' => []
            ]
        ]);
    }
    
    /**
     * 获取统计概览
     */
    public function getStatsOverview()
    {
        $today = now()->format('Y-m-d');
        $yesterday = now()->subDay()->format('Y-m-d');
        
        $todayStats = ApiStatistics::getDailyStatistics($today);
        $yesterdayStats = ApiStatistics::getDailyStatistics($yesterday);
        $currentHourStats = ApiStatistics::getHourlyStatistics();
        
        return response()->json([
            'success' => true,
            'message' => 'API统计概览',
            'data' => [
                'today' => $todayStats ?: ['total_requests' => 0, 'avg_response_time' => 0],
                'yesterday' => $yesterdayStats ?: ['total_requests' => 0, 'avg_response_time' => 0],
                'current_hour' => $currentHourStats ?: ['total_requests' => 0, 'avg_response_time' => 0],
                'summary' => [
                    'today_requests' => $todayStats['total_requests'] ?? 0,
                    'yesterday_requests' => $yesterdayStats['total_requests'] ?? 0,
                    'current_hour_requests' => $currentHourStats['total_requests'] ?? 0,
                    'growth_rate' => $this->calculateGrowthRate(
                        $todayStats['total_requests'] ?? 0,
                        $yesterdayStats['total_requests'] ?? 0
                    )
                ]
            ]
        ]);
    }
    
    /**
     * 计算增长率
     */
    private function calculateGrowthRate($today, $yesterday)
    {
        if ($yesterday == 0) {
            return $today > 0 ? 100 : 0;
        }
        
        return round(($today - $yesterday) / $yesterday * 100, 2);
    }




    
}
